﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using IHISCETeim.Model;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using FineUI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;


namespace IHISCETeim.Web.AgentSys.SvrMgr
{
    public partial class AgentQltySvrActList : AgentPageBase
    {

        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.查看 };
            }
        }
        protected override string DWZRef
        {
            get { return "AgentQltySvrActList"; }
        }

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (GetRequestValue<string>("SerialNumber", "") != "")
            {
                ttbSearchMessage.Text = GetRequestValue<string>("SerialNumber", "");
            }
            if (GetRequestValue<string>("ClaimsNumber", "") != "")
            {
                ttbSearchMessage.Text = GetRequestValue<string>("ClaimsNumber", "");
            }
            if (!IsPostBack)
            {
                this.tbxAgentName.Text = GetRequestValue<string>("AgentName","");
                this.FromIssueDate.Text = GetRequestValue<string>("FromIssueDate", "");
                this.ToIssueDate.Text = GetRequestValue<string>("ToIssueDate", "");
                this.IsYJGL.Text = GetRequestValue<string>("IsYJGL", "");
                this.NoNormative.Text = GetRequestValue<string>("NoNormative", "");
                // this.ttbSearchMessage.Text = GetRequestValue<string>("ClaimsNumber", "");
                LoadData();
            }
          
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerWithButton(Permission.新增, btnNew);
            CheckPowerWithButton(Permission.导出, btnExecl);
           
            // 每页记录数
            Grid1.PageSize = PageSize;
            ddlGridPageSize.SelectedValue = PageSize.ToString();

            BindGrid();
        }


        protected string GetSQLWhere()
        {
            string SeaVal = ttbSearchMessage.Text.Trim();

            string wheresql = "";          

            string sqlcommonFiled = "";
            if (!string.IsNullOrEmpty(SeaVal))
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("ClaimsNumber", QueryOperatorsEnum.包含, SeaVal);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " or " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }
            if (!string.IsNullOrEmpty(SeaVal))
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("SerialNumber", QueryOperatorsEnum.包含, SeaVal);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " or " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }
            if (!string.IsNullOrEmpty(SeaVal))
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("CustomerName", QueryOperatorsEnum.包含, SeaVal);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " or " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }
            if (!string.IsNullOrEmpty(SeaVal))
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("MachineType", QueryOperatorsEnum.包含, SeaVal);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " or " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }

            if (this.rblSearchSvrAct.SelectedValue == "my")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("SrvActUserId", QueryOperatorsEnum.等于, base.User.UserId.ToString());
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }

            if (this.FromIssueDate.Text != "")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("FaultDate", QueryOperatorsEnum.范围, this.FromIssueDate.Text + "|" + this.ToIssueDate.Text);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }

            if (this.FromPartsInDate.Text != "")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("NoticeSendPartsDate", QueryOperatorsEnum.范围, this.FromPartsInDate.Text + "|" + this.ToPartsInDate.Text);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }

            if (this.FromClaimsNumber.Text != "")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("ClaimsNumber", QueryOperatorsEnum.范围, this.FromClaimsNumber.Text + "|" + this.ToClaimsNumber.Text);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }
            if (this.tbxAgentName.Text != "")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("AgentName", QueryOperatorsEnum.包含, this.tbxAgentName.Text );
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }
            if (this.tbxSvrName.Text != "")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("SrvActRealName", QueryOperatorsEnum.包含, this.tbxSvrName.Text);
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }

            //2017-03-22 品情提报不完整报表和样机管理不当报表
            if (this.IsYJGL.Text != "")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("IsYJGL", QueryOperatorsEnum.等于, "1");
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }
            if (this.NoNormative.Text != "")
            {
                sqlcommonFiled = QueryOperatorsEnumHelper.ConvertCommonOperator("NoNormative", QueryOperatorsEnum.等于, "1");
                if (!string.IsNullOrEmpty(wheresql))
                {
                    wheresql += " and " + sqlcommonFiled;
                }
                else
                {
                    wheresql = sqlcommonFiled;
                }
            }

            return wheresql;
        }

        

        private void BindGrid()
        {
            CheckPowerWithLinkButtonField(Permission.删除, Grid1, "deleteField");
            //DataTableCollection dtc=
            Grid1.DataSource = AgentQltyController.GetPagination(GetSQLWhere(), Grid1.PageIndex + 1, Grid1.PageSize, Grid1.SortField + " " + Grid1.SortDirection, ref TotalCount)[0];          
            Grid1.DataBind();
            Grid1.RecordCount = TotalCount;
           
        }

        #endregion

        #region Events

        protected void ttbSearchMessage_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchMessage.ShowTrigger1 = true;
            // 更改每页显示数目时，防止 PageIndex 越界
            Grid1.PageIndex = 0;
            BindGrid();
        }

        protected void ttbSearchMessage_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchMessage.Text = String.Empty;
            ttbSearchMessage.ShowTrigger1 = false;
            // 更改每页显示数目时，防止 PageIndex 越界
            Grid1.PageIndex = 0;
            BindGrid();
        }

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }


        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            int QltyId = GetSelectedDataKeyID(Grid1);
            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!HasPower(Permission.删除))
                {
                    CheckPowerFailWithAlert();
                    return;
                }
                //执行删除代码  
                if (AgentQltyController.GetByQltyId(QltyId).ClaimState == "品情已确认")
                {
                    Alert.Show("对不起,此品情已确认,不能进行删除操作");
                    return;
                }
                if (AgentQltyController.GetByQltyId(QltyId).SrvActUserId == base.User.UserId)
                {
                    this.AddLog(Permission.删除, AgentQltyController.GetByQltyId(QltyId), "");
                    //删除操作
                    AgentQltyController.Delete(QltyId);
                    BindGrid();
                }                
                else
                {
                    Alert.Show("对不起,此经销商的担当不属于你,你不能进行删除操作");
                    return;
                }
            }
            if (e.CommandName == "selectSerialNumber")
            {
                Grid1.PageIndex = 0;
                this.ttbSearchMessage.Text = AgentQltyController.GetByQltyId(QltyId).SerialNumber;
                BindGrid();
            }
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);
            // 更改每页显示数目时，防止 PageIndex 越界
            if (Grid1.PageIndex > Grid1.PageCount - 1)
            {
                Grid1.PageIndex = Grid1.PageCount - 1;
            }
 
            BindGrid();
        }

        #endregion

        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
           
            DataRowView dr = e.DataItem as DataRowView;
            try
            {
                string ClaimStateVal = dr["ClaimState"].ToString();
                System.Web.UI.WebControls.HyperLink xx = Grid1.Rows[e.RowIndex].FindControl("hlClaimState") as System.Web.UI.WebControls.HyperLink;
                System.Web.UI.WebControls.HyperLink hlopenClaims = Grid1.Rows[e.RowIndex].FindControl("openClaims") as System.Web.UI.WebControls.HyperLink;
                System.Web.UI.WebControls.HyperLink execlClaims = Grid1.Rows[e.RowIndex].FindControl("execlClaims") as System.Web.UI.WebControls.HyperLink;

                System.Web.UI.WebControls.Label _lbSvrResult = Grid1.Rows[e.RowIndex].FindControl("lbSvrResult") as System.Web.UI.WebControls.Label;

                _lbSvrResult.Text = StringHelper.StripTags(dr["SvrResult"].ToString(), false);

                if (ClaimStateVal == ClaimState.品情再确认.ToString())
                {
                    xx.ToolTip = dr["CancelReason"].ToString();
                }
                xx.ForeColor = GetColorByClaimState(ClaimStateVal);
                //权限及 审核处理
                //if (ClaimStateVal == ClaimState.服务部长审核中.ToString() || ClaimStateVal == ClaimState.服务经理审核中.ToString())
                //{
                //    hlopenClaims.NavigateUrl = "javascript:openAgentQltySvrMgrEdit(" + dr["QltyId"] + ",'" + dr["ClaimsNumber"] + "')";
                //}
                //else { 
                    if (HasPower(new Permission[]{ Permission.修改,Permission.查看}))
                    {
                        hlopenClaims.NavigateUrl = "javascript:openAgentQltySvrAct(" + dr["QltyId"] + ",'" + dr["ClaimsNumber"] + "')";
                    }
                //}
                execlClaims.NavigateUrl = "javascript:openExecl(" + dr["QltyId"] + ")";
                //
               // CheckPowerFailWithLinkButtonField(Grid1, "btnView");
               //
                
                
             
            }
            catch
            {

            }
        }

        protected void rblSearchSvrAct_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 更改每页显示数目时，防止 PageIndex 越界
            Grid1.PageIndex = 0;
            BindGrid();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (FromIssueDate.Text == "" || ToIssueDate.Text == "")
            {
                FromIssueDate.Text = "";
                ToIssueDate.Text = "";  
            }
            if (FromClaimsNumber.Text == "" || ToClaimsNumber.Text == "")
            {
                FromClaimsNumber.Text = "";
                ToClaimsNumber.Text = "";
            }
            if (FromPartsInDate.Text == "" || ToPartsInDate.Text == "")
            {
                FromPartsInDate.Text = "";
                ToPartsInDate.Text = "";
            }
            // 更改每页显示数目时，防止 PageIndex 越界
            Grid1.PageIndex = 0;
            BindGrid();
        }

        protected void btnExecl_Click(object sender, EventArgs e)
        {
           // string url = this.ExportExcelWebUrl+"/AgentSys/AgentQlty.aspx?SearchMessage={0}&SearchSvrAct={1}&FromFaultDate={2}&ToFaultDate={3}";
            string url = this.ExportExcelWebUrl + "/AgentSys/AgentQlty.aspx?q=" + HttpContext.Current.Server.UrlEncode(  GetSQLWhere());
           // url = string.Format(url, ttbSearchMessage.Text, rblSearchSvrAct.SelectedValue, FromFaultDate.Text, ToFaultDate.Text);

            PageContext.RegisterStartupScript("top.window.open('" + url + "','','alwaysRaised=yes,z-look=yes,width=500,height=200,toolbar=no,location=no,directories=no,status=no,menubars=no,scrollbars=no,resizable=no')");

            
            //PageContext.Redirect(url, "_top");
        }

        protected void Grid1_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            DataRowView dr = e.DataItem as DataRowView;
            bool IsNeedAppove = Convert.ToBoolean(dr["IsNeedAppove"] is DBNull ? false : dr["IsNeedAppove"]);//是否需要通报
            bool IsAppove = Convert.ToBoolean(dr["IsAppove"] is DBNull ? false : dr["IsAppove"]);//是否已通报
            LinkButtonField lbField = Grid1.FindColumn("showSvrSchem") as LinkButtonField;
            //如果有需要通报
            if (IsNeedAppove)
            {
                if (IsAppove)
                {
                    //已审核
                    lbField.Icon = Icon.AwardStarSilver1;
                    lbField.Text = "已通报";
                    lbField.ToolTip = "已审核并抄送";
                }
                else
                {
                    lbField.Icon = Icon.AwardStarGold1;
                    lbField.Text = "未通报";
                    lbField.ToolTip = "未审核";
                }
            }
            else {
                lbField.Icon = Icon.None;
                lbField.Text = "";
                lbField.ToolTip = "";
            }
           
          //  FineUI.LinkButtonField execlField = Grid1.FindColumn("showSvrSchem") as FineUI.LinkButtonField;
           // xxxxxx.Icon = Icon.FeedAdd;
           // execlField.DataNavigateUrlFormatString = this.ExportExcelWebUrl + "/AgentSys/AgentQltyExeclSing.aspx?id={0}";

            WindowField execlClaims22 = Grid1.FindColumn("changePartsSend") as WindowField;
            DateTime RealSendDate = Convert.ToDateTime(dr["RealSendDate"] is DBNull ? null : dr["RealSendDate"]);//配件发货时间
            if (RealSendDate>DateTime.MinValue)
                execlClaims22.Text = "&nbsp[已发]";
            else
                execlClaims22.Text = "";
            //20161025 质管指派担当
            WindowField execlZLAssignRealName = Grid1.FindColumn("changeZLAssignRealName") as WindowField;
            DateTime _ZLAssignDate = Convert.ToDateTime(dr["ZLAssignDate"] is DBNull ? null : dr["ZLAssignDate"]);//指派时间
            string _ZLAssignRealName= Convert.ToString(dr["ZLAssignRealName"] is DBNull ? null : dr["ZLAssignRealName"]);//人员

            if (string.IsNullOrEmpty(_ZLAssignRealName))
            {
                execlZLAssignRealName.Text = "指派担当";
                execlZLAssignRealName.ToolTip = "点击可指派担当";
            }
            else {
                execlZLAssignRealName.Text = _ZLAssignRealName + _ZLAssignDate.ToString("yyyy-MM-dd");
            }
           
            //20161025 对策报告（扫描后上传）
            WindowField execlZLSituationReport = Grid1.FindColumn("changeZLSituationReport") as WindowField;
            DateTime _ZLSituationDate = Convert.ToDateTime(dr["ZLSituationDate"] is DBNull ? null : dr["ZLSituationDate"]);//对策日期
            string _ZLSituationReport = Convert.ToString(dr["ZLSituationReport"] is DBNull ? null : dr["ZLSituationReport"]);//对策报告

            if (string.IsNullOrEmpty(_ZLSituationReport))
            {
                execlZLSituationReport.Text = "上传";
                execlZLSituationReport.ToolTip = "点击可上传对策报告（扫描件）";
            }
            else {
                execlZLSituationReport.Text =_ZLAssignDate.ToString("yyyy-MM-dd");
            }

        }

        protected void btnBatchExecl_Click(object sender, EventArgs e)
        {
            // string url = this.ExportExcelWebUrl+"/AgentSys/AgentQlty.aspx?SearchMessage={0}&SearchSvrAct={1}&FromFaultDate={2}&ToFaultDate={3}";
            string url = this.ExportExcelWebUrl + "/AgentSys/AgentQltyBatchExecl.aspx?q=" + HttpContext.Current.Server.UrlEncode(GetSQLWhere());
            // url = string.Format(url, ttbSearchMessage.Text, rblSearchSvrAct.SelectedValue, FromFaultDate.Text, ToFaultDate.Text);

            PageContext.RegisterStartupScript("top.window.open('" + url + "','','alwaysRaised=yes,z-look=yes,width=500,height=200,toolbar=no,location=no,directories=no,status=no,menubars=no,scrollbars=no,resizable=no')");


            //PageContext.Redirect(url, "_top");
        }
    }
}